from dbUtil import DBUtil as Mydb

class MyService:
    def __init__(self):
        self.user = None
    def login(self,username,password):
        sql = 'select * from t_user where username = %s and password = %s'
        user = Mydb().query_one(sql, username, password)
        if user:
            self.user = user
            return True
        else:
            return False

    def addMusic(self,files):
        for musicfile in files:
            start  = musicfile.rfind('/')+1;
            end = musicfile.rfind('.mp3')
            #获取音乐名
            musicname = musicfile[start:end]
            #创建用户对象

            sql = "select * from t_music"
            AllResult = Mydb().query_all(sql)

            #t_music id
            musicId = 0;
            if AllResult:
                musicId = (AllResult[len(AllResult) - 1][0] + 1)
                print(f'musicId:{0}'.format(musicId))
                # 将音乐保存到t_music表
                sql = "insert into t_music values (%s,%s,%s)"
            else:
                musicId = 1
                print(f'musicId:{0}'.format(musicId))
                # 将音乐保存到t_music表
                sql = "insert into t_music values (%s,%s,%s)"



            #根据歌名进行查询数据库是否存在改歌曲
            musicNameSelect = 'select * from t_music where musicName = %s'
            #进行查询插入音乐在用户音乐列表是否存在
            music = Mydb().query_one(musicNameSelect,musicname)
            if music:
                #查询关联表 查询用户是否添加了这首歌
                tSql = 'select * from t_list where mid = %s and uid = %s'
                tList = Mydb().query_one(tSql,music[0],self.user[0])
                if not tList:
                    tSql = "insert into t_list(mid,uid) values(%s,%s)"
                    Mydb().exeDML(tSql, music[0], self.user[0])
                    print("{}.mp3音乐已经在{}用户音乐列表上添加成功.".format(musicname, self.user[1]))
                else:
                    print("{}.mp3音乐已经在{}用户音乐列表上已存在.".format(musicname, self.user[1]))
            else:
                Mydb().exeDML(sql,musicId,musicname,musicfile)
                sql ="insert into t_list(mid,uid) values(%s,%s)"
                Mydb().exeDML(sql,musicId,self.user[0])
                print(f"{musicname}.mp3音乐已经在{self.user[1]}音乐列表上添加成功.")
            #用户选择的音乐保存到t_list中


